package com.weizhizs.assistant.code.template;

import com.weizhizs.assistant.code.TestCodeGenerator;
import com.weizhizs.assistant.code.helper.FileHelper;
import com.weizhizs.assistant.code.vo.TableVO;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.StringWriter;
import java.util.Map;
import java.util.Properties;

public class TestVelocityGenerator implements TestCodeGenerator {

    @Override
    public void run(TableVO tableVO) {
        //设置velocity资源加载器
        Properties prop = new Properties();
        prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(prop);

        String tableName = tableVO.getTableName();

        //获取模板列表
        Map<String, TestDataLoador> templateMap = TestDataRegister.templateDataMap();
        for (String template : templateMap.keySet()) {
            TestDataLoador templateData = templateMap.get(template);
            Map<String, Object> dataMap = templateData.getDataMap(tableVO);
            if (null != dataMap) {
                VelocityContext context = new VelocityContext(dataMap);

                //渲染模板
                StringWriter sw = new StringWriter();
                Template tpl = Velocity.getTemplate(templateData.getTemplateName(tableVO), "UTF-8");
                tpl.merge(context, sw);

                FileHelper.saveToFile(templateData.getFileOutPath(), sw.toString(), templateData.getFileName(tableName));
            }
        }
    }
}
